// components/player/index.tsx
import React, { useState } from "react";
import "./index.scss";
import { Tag, Popup } from "antd-mobile";
import { DownOutline } from "antd-mobile-icons";
import { usePlayerStore } from "../../store/player";
import { useEffect, useLayoutEffect } from "react";
import { useRef } from "react";
import { TouchEventHandler } from "react";
type Props = {};
const timeHandler = (second: number) => {
  let m = Math.floor(second / 60);
  let s = Math.round(second % 60);
  let mStr = m >= 10 ? m : `0${m}`;
  let sStr = s >= 10 ? s : `0${s}`;
  return `${mStr}:${sStr}`;
};
let duration = 0; //音频总时长
let barWidth = 0; //进度条最大宽度
let beginX = 0; //记录按下时鼠标横轴坐标
let beginW = 0; //按下时进度条的宽度
export default function AudioPlay({}: Props) {
  const { show, toggleShow, popData, isPlay, togglePlay, toggleBubbleShow } =
    usePlayerStore((state) => state);
  const audioRef = useRef<HTMLAudioElement>(null);
  const barRef = useRef<HTMLDivElement>(null);
  const [move, setMove] = useState<number>(0);
  const [timeNow, setTimeNow] = useState<string>("00:00");
  const [timeMax, setTimeMax] = useState<string>("00:00");
  //确保音频准备好后再提取时长
  const handleCanPlay = () => {
    let ele = audioRef.current as HTMLAudioElement;
    let bar = barRef.current as HTMLDivElement;
    duration = ele.duration;
    barWidth = bar.offsetWidth;
    console.log(duration, barWidth);
    setTimeMax(timeHandler(duration)); //显示音频总时长
  };
  const handleTimeUpdate = () => {
    let ele = audioRef.current as HTMLAudioElement;
    let curTime = ele.currentTime;
    console.log("当前播放时间", curTime);
    let m = (curTime / duration) * barWidth;
    setMove(m);
    setTimeNow(timeHandler(curTime)); //修改当前播放时间
  };
  const handlePlay = (bool: boolean) => {
    togglePlay(bool);
  };
  //检测isPlay变化，执行音频播放控制
  useEffect(() => {
    let ele = audioRef.current;
    console.log(duration, barWidth);
    if (isPlay) {
      ele?.play();
    } else {
      ele?.pause();
    }
  }, [isPlay]);
  const handleStart: TouchEventHandler<HTMLDivElement> = (ev) => {
    console.log(ev);
    beginX = ev.changedTouches[0].clientX;
    beginW = move;
  };
  const handleMove: TouchEventHandler<HTMLDivElement> = (ev) => {
    console.log(ev, beginX, beginW);
    let nowX = ev.changedTouches[0].clientX;
    let m = nowX - beginX + beginW;
    let nowTime = (m / barWidth) * duration;
    let ele = audioRef.current as HTMLAudioElement;
    if (m <= barWidth) {
      setMove(m);
      ele.currentTime = nowTime;
    }
  };
  const handleClose = () => {
    toggleShow(false);
    if (isPlay) {
      toggleBubbleShow(true);
    }
  };

  return (
    <Popup bodyStyle={{ height: "100vh" }} visible={show}>
      <div className="audio-play">
        <div className="drop-cont">
          <DownOutline fontSize={20} onClick={handleClose} />
          <Tag color="default">耀眼的播放器</Tag>
          <span></span>
        </div>
        <div className={`play-btn ${isPlay ? "" : "stop"}`}>
          <i
            className="iconfont bofang_bg"
            onClick={() => {
              handlePlay(true);
            }}
          ></i>
          <i
            className="iconfont zanting1_bg"
            onClick={() => {
              handlePlay(false);
            }}
          ></i>
          <i className="iconfont zanting_bg"></i>
        </div>
        <div className="audio-control">
          <audio
            ref={audioRef}
            src={popData ? popData.music : ""}
            onCanPlay={handleCanPlay}
            onTimeUpdate={handleTimeUpdate}
          ></audio>
          <div className="icon-cont">
            <i className="iconfont jushoucang"></i>
            <i className="iconfont fenxiang"></i>
          </div>
          <div className="bar" ref={barRef}>
            <div className="inner" style={{ width: `${move}px` }}>
              <div
                className="dot"
                onTouchStart={handleStart}
                onTouchMove={handleMove}
              ></div>
            </div>
          </div>
          <div className="time-cont">
            <span>{timeNow}</span>
            <span>{timeMax}</span>
          </div>
        </div>
        <div className="circle circle1"></div>
        <div className="circle circle2"></div>
        <div className="circle circle3"></div>
      </div>
    </Popup>
  );
}
